package com.example.moshudriver.activity;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.MyProgressDialog;
import com.BeeFramework.view.ToastView;
import com.sgr.dykdriver.R;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.external.androidquery.callback.AjaxStatus;
import com.google.gson.Gson;
import com.pingplusplus.android.PaymentActivity;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.unionpay.UPPayAssistEx;

public class RechargeActivity extends Activity implements OnClickListener,BusinessResponse{
 TextView	top_view_title,top_view_right_text;
 Button recharge_button;
 EditText recharge_edit;
 ImageView top_view_back;
 LinearLayout alipayButton,wechatButton,upmpButton;
 public static final String URL =ApiInterface.URL_PAY+"api/withdraw/payd";
 private static final int REQUEST_CODE_PAYMENT = 1;
 
 /**
  * 银联支付渠道
  */
 private static final String CHANNEL_UPMP = "upmp";
 /**
  * 微信支付渠道
  */
 private static final String CHANNEL_WECHAT = "wx";
 /**
  * 支付支付渠道
  */
 private static final String CHANNEL_ALIPAY = "alipay";
 /**
  * 百度支付渠道
  */
 private static final String CHANNEL_BFB = "bfb";
 /**
  * 京东支付渠道
  */
 private static final String CHANNEL_JDPAY_WAP = "jdpay_wap";
 UserBalanceModel withdrawModel;
 MyProgressDialog pro;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recharge);
		initView();
		withdrawModel=new UserBalanceModel(this);
		withdrawModel.addResponseListener(this);
	}
    private void initView(){
    	top_view_title=(TextView)findViewById(R.id.top_view_title);
    	top_view_title.setText(R.string.recharge);
    	top_view_right_text=(TextView)findViewById(R.id.top_view_right_text);
    	top_view_right_text.setVisibility(View.VISIBLE);
    	top_view_right_text.setText(R.string.recharge_record);
    	top_view_right_text.setOnClickListener(this);
    	recharge_edit=(EditText)findViewById(R.id.recharge_edit);
    	alipayButton=(LinearLayout)findViewById(R.id.alipayButton);
    	wechatButton=(LinearLayout)findViewById(R.id.wechatButton);
    	upmpButton=(LinearLayout)findViewById(R.id.upmpButton);
    	top_view_back=(ImageView)findViewById(R.id.top_view_back);
    	top_view_back.setOnClickListener(this);
    	alipayButton.setOnClickListener(this);
    	wechatButton.setOnClickListener(this);
    	upmpButton.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		
		case R.id.alipayButton:	
			if(recharge_edit.getText().toString()!=null&&!"".equals(recharge_edit.getText().toString())){
				pro = new MyProgressDialog(RechargeActivity.this, "请稍候...");
				pro.show();
				new PaymentTask().execute(new PaymentRequest(CHANNEL_ALIPAY, Float.parseFloat(recharge_edit.getText().toString())*100));
			}else{
				Toast.makeText(RechargeActivity.this, R.string.fill_in_money, 2000).show();
			}
			 
			break;
		case R.id.wechatButton:
			if(recharge_edit.getText().toString()!=null&&!"".equals(recharge_edit.getText().toString())){
				pro = new MyProgressDialog(RechargeActivity.this, "请稍候...");
				pro.show();
				new PaymentTask().execute(new PaymentRequest(CHANNEL_WECHAT, Float.parseFloat(recharge_edit.getText().toString())*100));
			}else{
				Toast.makeText(RechargeActivity.this, R.string.fill_in_money, 2000).show();
			}
			break;
		case R.id.upmpButton:
			if(recharge_edit.getText().toString()!=null&&!"".equals(recharge_edit.getText().toString())){
				pro = new MyProgressDialog(RechargeActivity.this, "请稍候...");
				pro.show();
				new PaymentTask().execute(new PaymentRequest(CHANNEL_UPMP, Float.parseFloat(recharge_edit.getText().toString())*100));
			}else{
				Toast.makeText(RechargeActivity.this, R.string.fill_in_money, 2000).show();
			}
        
		break;
		case R.id.top_view_back:
			finish();
			break;
		case R.id.top_view_right_text:

			Intent intent1=new Intent();
			intent1.setClass(RechargeActivity.this,Recharge_recordActivity.class);
			startActivity(intent1);
			break;
			
		}
		
	}
	
	class PaymentTask extends AsyncTask<PaymentRequest, Void, String> {

		@Override
		protected void onPreExecute() {

			// 按键点击之后的禁用，防止重复点击
			wechatButton.setClickable(false);
			alipayButton.setClickable(false);
			upmpButton.setClickable(false);
			

		}

		@Override
		protected String doInBackground(PaymentRequest... pr) {
			System.out.println("pr" + pr);
			PaymentRequest paymentRequest = pr[0];
			String data = null;
			String json = new Gson().toJson(paymentRequest);
			System.out.println("paymentRequest" + paymentRequest);
			System.out.println("json" + json);
			try {
				// 向Your Ping++ Server SDK请求数据
				data = postJson(URL, json);
				System.out.println("data" + data);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		/**
		 * 获得服务端的charge，调用ping++ sdk。
		 */
		@Override
		protected void onPostExecute(String data) {
			if(pro!=null){
				pro.dismiss();
			}
			
			System.out.println("data_ping" + data);
			if (null == data) {
				ToastView.toast.makeText(RechargeActivity.this, "请求出错", 2000).show();
//				showMsg("请求出错", "请检查URL", "URL无法获取charge");
				return;
			}
			Log.d("charge", data);
			Intent intent = new Intent();
			String packageName = getPackageName();
			ComponentName componentName = new ComponentName(packageName,
					packageName + ".wxapi.WXPayEntryActivity");
			intent.setComponent(componentName);
			intent.putExtra(PaymentActivity.EXTRA_CHARGE, data);
			startActivityForResult(intent, REQUEST_CODE_PAYMENT);
		}

	}
	private static String postJson(String url, String json) throws IOException {
		MediaType type = MediaType.parse("application/json; charset=utf-8");
		RequestBody body = RequestBody.create(type, json);
		Request request = new Request.Builder().url(url).post(body).build();

		OkHttpClient client = new OkHttpClient();
		Response response = client.newCall(request).execute();

		return response.body().string();
	}
	class PaymentRequest {
		String channel;
		float amount;
		String orderNo;

		public PaymentRequest(String channel, float amount) {
			this.channel = channel;
			this.amount = amount;
			this.orderNo = orderNo;
		}
	}
	/**
	 * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。 最终支付成功根据异步通知为准
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		wechatButton.setClickable(true);
		upmpButton.setClickable(true);
		alipayButton.setClickable(true);
		

		// 支付页面返回处理
		if (requestCode == REQUEST_CODE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				String result = data.getExtras().getString("pay_result");
				/*
				 * 处理返回值 "success" - payment succeed "fail" - payment failed
				 * "cancel" - user canceld "invalid" - payment plugin not
				 * installed
				 */
				String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
				String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
				System.out.println("result" + result + "errorMsg" + errorMsg
						+ "extraMsg" + extraMsg);
				if(result.equals("success")){//					支付成功
					withdrawModel.InMoney(recharge_edit.getText().toString());
                      ToastView.toast.makeText(RechargeActivity.this, "支付成功", 2000).show();
//                      mOrderInfoModel.pay(mOrderId, ENUM_PAY_CODE.PAY_ONLINE.value());
//                      支付成功之后就要给司机加额度，并且改变 订单状态，并且提醒司机支付成功 ，写个接口
				}else if(result.equals("fail")){
					 ToastView.toast.makeText(RechargeActivity.this, "支付失败", 2000).show();
				}else if(result.equals("cancel")){
					 ToastView.toast.makeText(RechargeActivity.this, "取消支付", 2000).show();
				}else if(result.equals("invalid")){
					 UPPayAssistEx.installUPPayPlugin(this); //安装银联安全支付控件
				}
			
			}
		}

	}
	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if(url.endsWith(ApiInterface.WITHDRAW_INMONEY)){
			Toast.makeText(this, R.string.inmoney_success, 2000).show();//充值成功
			RechargeActivity.this.finish();
		}
		
	}
	
}
